package org.example.Voutils;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket {
    private static AtomicInteger numberb= new AtomicInteger(30);
   // private  Integer number = 30;
    private Lock lock = new ReentrantLock(true);

    public static synchronized void sale1() {
        int number = numberb.getAndDecrement();
        if (number <= 0) {
            System.out.println(Thread.currentThread().getName() + "票已经卖完");
            return;
        }
        try {
            System.out.println(Thread.currentThread().getName() + "开始售票,当前有" + number + "票");
            if (Thread.currentThread().getName().equals("A")) {
                Thread.sleep(250);
            } else {
                Thread.sleep(200);
            }

            System.out.println(Thread.currentThread().getName() + "售票结束,剩余有" + number-- + "票");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
        }

    }
    public void sale2(){
        lock.lock();
        int number = numberb.getAndDecrement();
        if(number<=0){
            System.out.println(Thread.currentThread().getName()+"票已经卖完");
            lock.unlock();
        return;
        }
        try {
            System.out.println(Thread.currentThread().getName()+"开始售票,当前有"+number--+"票");
            if(Thread.currentThread().getName().equals("A")){
                Thread.sleep(250);
            }else{
                Thread.sleep(200);
            }

            System.out.println(Thread.currentThread().getName() + "售票结束,剩余有" + number-- + "票");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            lock.unlock();
        }

    }

}
